package com.asj.house.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.asj.house.constant.RedisConstants;
import com.asj.house.entity.HouseMenu;
import com.asj.house.entity.HouseUser;
import com.asj.house.mapper.HouseUserMapper;
import com.asj.house.returns.RespCode;
import com.asj.house.returns.RespEntity;
import com.asj.house.returns.RespTable;
import com.asj.house.service.HouseUserService;
import com.asj.house.utils.RedisUtil;
import com.asj.house.vo.param.LoginParam;
import com.asj.house.vo.param.UserParam;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author asj
 * @since 2021-03-16
 */
@Service
@Slf4j
public class HouseUserServiceImpl extends ServiceImpl<HouseUserMapper, HouseUser> implements HouseUserService {

    @Autowired
    private RedisUtil redisUtil;

    @Value("${cloud.sms.url}")
    private String url;

    @Value("${cloud.sms.username}")
    private String username;

    @Value("${cloud.sms.password}")
    private String password;

    @Override
    public RespEntity<HouseUser> login(LoginParam loginParam) {
        QueryWrapper<HouseUser> queryWrapper = new QueryWrapper();

        queryWrapper.lambda().eq(HouseUser::getMobile, loginParam.getMobile())
                .eq(HouseUser::getAdmin, 1);

        HouseUser houseUser = baseMapper.selectOne(queryWrapper);
        if (Objects.isNull(houseUser)) {
            return new RespEntity<>(RespCode.NOT_ADMIN);
        }

        //按照账号和密码查询用户信息
        queryWrapper.lambda().eq(HouseUser::getName, loginParam.getUsername())
                .eq(HouseUser::getPassword, loginParam.getPassword());

        HouseUser user = baseMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            return new RespEntity(RespCode.NOT_FOUND);
        }

        return new RespEntity(RespCode.SUCCESS, user);
    }

    @Override
    public RespTable<List<HouseUser>> queryAllUser(UserParam userParam) {
        QueryWrapper<HouseUser> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(userParam.getColumn()) && Objects.nonNull(userParam.getValue())) {
            queryWrapper.like(userParam.getColumn(), userParam.getValue());
        }
        queryWrapper.lambda().eq(HouseUser::getDeleted, 0)
                .orderByDesc(HouseUser::getCreatedDate);

        IPage<HouseUser> iPage = new Page<>(userParam.getPage(), userParam.getLimit());
        IPage<HouseUser> page = super.page(iPage, queryWrapper);
        return new RespTable(RespCode.OK, page.getRecords(), page.getTotal());
    }

    @Override
    public RespEntity<Integer> sendMsg(String mobile) {
        //随机生成6位数字验证码
        String code = RandomUtil.randomNumbers(6);
        //发送短信验证码
        String ok = send(mobile, code);
        if (StringUtils.isBlank(ok)) {
            return new RespEntity(RespCode.NOT_FOUND);
        }
        //获取短信验证码 间隔时间
        Integer time = 60;
        //code保存redis 并设置过期时间
        redisUtil.set(RedisConstants.key.getSMS(mobile), code, time);

        return new RespEntity(RespCode.SUCCESS, time);
    }

    /**
     * 发送短信验证码
     * @param mobile
     * @param code
     * @return
     */
    private String send(String mobile, String code) {

        String content = template(mobile, code);
        log.info("发送短信模板为：content={}", content);

        String smsUrl = url + "?username=" + username + "" +
                "&password=" + password + "&mobile=" + mobile + "&content=" + content;

        String response = HttpUtil.get(smsUrl);
        log.info("短信发送数据返回，response={}", response);

        Map respMap = JSONUtil.toBean(response, Map.class);
        Integer result = (Integer) respMap.get("result");
        if (result.equals(0)) {
            return "OK";
        }
        return null;
    }

    private String template(String mobile, String code) {
        String template = "您的手机号：{}，登陆验证码：{}，一分钟内登陆有效，如不是本人操作请忽略！【NY租赁社区】";
        return StrUtil.format(template, mobile, code);
    }
}
